package Chuong06;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ThreadDemo1 extends JFrame implements Runnable{
	Thread t;
	JTextField textField = new JTextField();
	JPanel canvas = new JPanel();
	JButton
		b1 = new JButton("Start"), 
		b2 = new JButton("Suspend"),
		b3 = new JButton("Resume"),
		b4 = new JButton("Stop");
	
	public ThreadDemo1(){
		super("Thread Demo 2");
		add(canvas, BorderLayout.CENTER);
		canvas.setBackground(Color.ORANGE);
		
		JPanel panelButton = new JPanel();
		panelButton.setLayout(new FlowLayout());
		panelButton.add(b1);
		panelButton.add(b2);
		panelButton.add(b3);
		panelButton.add(b4);
		b1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				t.start();
				textField.setText("Running...");
			}
		}
		);
		b2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				t.suspend();
				textField.setText("Suspending...");
			}
		}
		);
		b3.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				t.resume();
				textField.setText("Continuing to draw...");
			}
		}
		);
		b4.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				t.stop();
				textField.setText("Stopped");
			}
		}
		);
		add(panelButton, BorderLayout.SOUTH);
		add(textField,BorderLayout.NORTH);
		
		//canvas.addMouseListener(new ML());
		setSize(new Dimension(400,400));
		t = new Thread(this);
	}
	
	public void run(){
		double width = 400.0;//(double)size().width;
		double height = 400.0;//(double)size().height;
		while(true){
			Graphics g = canvas.getGraphics();
			Color c = new Color((int)(255.0*Math.random()),
								(int)(255.0*Math.random()),
								(int)(255.0*Math.random()));
			g.setColor(c);
			g.fillRect((int)(width*Math.random()),
					   (int)(height*Math.random()),
					   (int)(width*Math.random()),
					   (int)(height*Math.random()));
			try{
				Thread.sleep(100);
			}
			catch(InterruptedException e){}
		}
	}
	
	public static void main(String[] args){
		ThreadDemo1 frame = new ThreadDemo1();
		frame.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		}
		);
		frame.setVisible(true);
	}
}
